from django.db import models
from django.contrib.auth.models import User

#Forum Class
class Forum(models.Model):
    title = models.CharField(max_length = 100, unique=True)
    description = models.CharField(max_length = 200)
    order = models.IntegerField()
    
    def __unicode__(self):
        return u"%s" % self.title
    
#On deletion, the delete cascades to the threads    
    def delete(self):
        for thread in self.getThreads():
            thread.delete()
        super(Forum, self).delete()
    
    class Meta:
        ordering = ['order']
        
#Returns all of the threads in the forum  
    def getThreads(self):
        return Thread.objects.filter(forum = self)

#Gets the number of post in all the threads in the forum        
    def postCount(self):
        if self.getThreads():
            posts = 0
            for thread in self.getThreads():
                posts += thread.getForumPosts().count()
            return posts
        else:
            return 0

#Returns the date of the most recent post in the forum            
    def lastPostDate(self):
        if not self.getThreads():
            return None
        return self.getThreads()[0].lastPostDate
        

#Thread class        
class Thread(models.Model):
    title = models.CharField(max_length=100)
    lastPostDate = models.DateTimeField(null=True, blank=True)
    lastPostAuthor = models.ForeignKey(
                        User, null=True, blank=True,
                        related_name="thread_lastPoster")
    forum = models.ForeignKey(Forum, null=False, blank=False)
    locked = models.BooleanField(default=False)
    sticky = models.BooleanField(default=False)
    
    def __unicode__(self):
        return u"%s" % self.title

#On deletion, the delete cascades to all of the forum posts in the thread
    def delete(self):
        for forumpost in self.getForumPosts():
            forumpost.delete()
        super(Thread, self).delete()
    
    class Meta:
        ordering = ['-sticky', '-lastPostDate']
        
#Get all forum posts in the thread
    def getForumPosts(self):
        return ForumPost.objects.filter(thread=self)

#Get the author of the first post in the thread        
    def getAuthor(self):
        return self.getForumPosts()[0].author
 
#Get the most recent post in the thread 
    def getLastPost(self):
        return self.getForumPosts().order_by('-datePosted')[0]
        

#Forum Post class        
class ForumPost(models.Model):
    body = models.TextField()
    author = models.ForeignKey(User, related_name="forumpost_author")
    datePosted = models.DateTimeField(auto_now_add=True)
    editor = models.ForeignKey(
                        User, null=True, blank=True, 
                        related_name="forumpost_editor")
    dateEdited = models.DateTimeField(null=True, blank=True)
    thread = models.ForeignKey(Thread)
    deleted = models.BooleanField(default=False)
    
    def __unicode__(self):
        return u"Forum post by %s on %s in thread %s"%(
                        self.author.username,
                        str(self.datePosted),
                        self.thread.title)
        
    class Meta:
        ordering = ['datePosted']
        
#Updates the thread's last posted date whenever a new comment is posted and saves the comment
    def save(self, force_insert=False, force_update=False):
        super(ForumPost, self).save(force_insert, force_update)
        
        if not self.thread.lastPostDate or self.datePosted > self.thread.lastPostDate:
            self.thread.lastPostDate = self.datePosted
            self.thread.lastPostAuthor = self.author
            self.thread.save()
 
#Finds the number of posts in a thread posted before this post
    def getPostNumber(self):
        num = 0
        for forumpost in self.thread.getForumPosts():
            if forumpost == self: return num
            num += 1